package com.fang.algorithm.leecode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 二叉树的左视图
 * 给定一个二叉树的 根节点 root，想象自己站在它的左侧，按照从顶部到底部的顺序，返回从左侧所能看到的节点值
 * 输入: [1,2,3,null,5,null,4]
 * 输出: [1,2,5]
 * <p>
 * 输入: [1,null,3]
 * 输出: [1,3]
 * @date 2022/5/16 10:46 上午
 **/
public class L199_Test_LeftSideView {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1, new TreeNode(2, null, new TreeNode(5)), new TreeNode(3, null, new TreeNode(4)));
        List<Integer> ans = leftSideView1(root);
//        List<Integer> ans = leftSideView2(root);
        System.out.println(ans);
    }

    /**
     * 广度优先遍历算法BFS
     */
    private static List<Integer> leftSideView1(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (null == root) {
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int currentSize = queue.size();
            for (int i = 0; i < currentSize; i++) {
                TreeNode node = queue.poll();
                if (null == node) {
                    continue;
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (i == currentSize - 1) {
                    ans.add(node.val);
                }
            }
        }
        return ans;
    }

    /**
     * 深度优先遍历算法DFS
     * 先序遍历 跟节点->左子树->右子树
     * 中序遍历 左子树->跟节点->右子树
     * 后续遍历 跟节点->右子树->左子树
     */
    private static List<Integer> leftSideView2(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        dfs(root, 0, ans);
        return ans;
    }

    private static void dfs(TreeNode root, int depth, List<Integer> ans) {
        if (null == root) {
            return;
        }
        if (depth == ans.size()) {
            ans.add(root.val);
        }
        depth++;
        dfs(root.left, depth, ans);
        dfs(root.right, depth, ans);
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
